<template>
  <div class="page praticle-page flex-col">
    <div class="box_1 flex-row">
      <div class="group_1 ">
        <img class="label_4" src="@/assets/ide/liebiao.png" />
        <span>{{ examTitle ? examTitle : '精选题库' }}</span>
        <el-countdown v-if="examEndTime && new Date() < new Date(examEndTime)" class="exam-time-countdown"
          @finish="handleCountdownFinish" title="距离竞赛结束还有:" :value="new Date(examEndTime)" />
      </div>
      <div class="group_2">
        <el-button type="primary" plain @click="submitQuestion">提交代码</el-button>
      </div>
      <span class="ide-back" @click="goBack()">返回</span>
    </div>
    <div class="box_8 flex-col">
      <div class="group_12 flex-row justify-between">
        <div class="image-wrapper_1 flex-row">
          <img class="thumbnail_2" src="@/assets/ide/xiaobiaoti.png" />
          <div class="question-nav">
            <span>题目描述</span>
          </div>
          <div class="question-nav" @click="preQuestion">
            <el-icon>
              <span>上一题</span>
              <ArrowLeft />
            </el-icon>
          </div>
          <div class="question-nav" @click="nextQuestion">
            <el-icon>
              <ArrowRight />
              <span>下一题</span>
            </el-icon>
          </div>
        </div>
        <div class="image-wrapper_2 flex-row">
          <img class="image_1" src="@/assets/ide/daima.png" />
          代码
        </div>
      </div>
      <div class="group_13 flex-row justify-between">
        <div class="box_3 flex-col">
          <span class="question-title">{{ questionDetail.title }}</span>
          <span class="question-limit">
            <div v-if="questionDetail.difficulty === 1">题目难度：简单 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
            <div v-if="questionDetail.difficulty === 2">题目难度：中等 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
            <div v-if="questionDetail.difficulty === 3">题目难度：困难 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
          </span>
          <span class="question-content" v-html="questionDetail.content"></span>
        </div>
        <div class="group_14 flex-col">
          <div class="group_8 flex-col">
            <codeEditor ref="defaultCodeRef" @update:value="handleEditorContent">
            </codeEditor>
          </div>
          <div class="code-result flex-row">
            <img class="code-result-image" src="@/assets/ide/codeResult.png" />
            <span class="code-result-content">执行结果</span>
          </div>
          <div class="group_15 flex-row">
            <div class="section_1 flex-row">
              <div class="section_3 flex-col">
                <div class="text-wrapper_2 flex-row justify-between">
                  <span class="text_1 red" v-if="userQuestionResultVO.pass === 0">未通过</span>
                  <span class="text_1 success" v-if="userQuestionResultVO.pass === 1">通过</span>
                  <span class="text_1 warning" v-if="userQuestionResultVO.pass === 2">请先执行代码</span>
                  <span class="text_1 info" v-if="userQuestionResultVO.pass === 3">系统正在处理您的代码，请稍后</span>
                </div>
                <span class="error-text" v-if="userQuestionResultVO.pass === 0">异常信息：{{
                  userQuestionResultVO.exeMessage }}</span>
                <el-table v-if="userQuestionResultVO.userExeResultList && userQuestionResultVO.userExeResultList.length > 0"
                  :data="userQuestionResultVO.userExeResultList">
                  <el-table-column prop="input" label="输入" />
                  <el-table-column prop="output" label="预期结果" />
                  <el-table-column prop="exeOutput" label="实际输出" />
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from "vue"
import codeEditor from "@/components/CodeEditor.vue"
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { useRoute } from "vue-router"
import { getQuestionDetailService, preQuestionService, nextQuestionService, getQuestionResultService } from "@/apis/question"
import router from "@/router"
import { examNextQuestionService, examPreQuestionService, getExamFirstQuestionService } from "@/apis/exam"
import { ElMessage } from "element-plus"
import { userSubmitService } from "@/apis/user"

function goBack() {
  router.go(-1)
}

const questionDetail = reactive({})
const defaultCodeRef = ref()

let questionId = useRoute().query.questionId
let examId = useRoute().query.examId
let examTitle = useRoute().query.examTitle
let examEndTime = useRoute().query.examEndTime

async function getQuestionDetail() {
  if (!questionId) {
    ElMessage.error('题目ID不能为空')
    router.push('/c-oj/home/question')
    return
  }
  
  if (examId && (questionId == null || questionId == '')) {
    const eqrs = await getExamFirstQuestionService(examId)
    questionId = eqrs.data
  }
  
  try {
    const res = await getQuestionDetailService(questionId)
    Object.assign(questionDetail, res.data)
    if (defaultCodeRef.value) {
      defaultCodeRef.value.setAceCode(questionDetail.defaultCode || '')
    } else {
      console.warn('代码编辑器组件未挂载')
    }
  } catch (error) {
    ElMessage.error('获取题目详情失败')
    console.error('获取题目详情失败：', error)
  }
}

onMounted(() => {
  getQuestionDetail()
})

onBeforeUnmount(() => {
  stopPolling()
})

async function preQuestion() {
  if (examId) {
    //竞赛中上一题的逻辑  需要提供一个竞赛中获取上一题的接口
    const res = await examPreQuestionService(examId, questionId)
    questionId = res.data
  } else {
    const res = await preQuestionService(questionId)
    questionId = res.data
  }
  getQuestionDetail()
}

async function nextQuestion() {
  if (examId) {
    //竞赛中下一题的逻辑 需要提供一个竞赛中获取下一题的接口
    const res = await examNextQuestionService(examId, questionId)
    questionId = res.data
  } else {
    const res = await nextQuestionService(questionId)
    questionId = res.data
  }
  getQuestionDetail()
}

function handleCountdownFinish() {
  ElMessage.info('竞赛已经结束了哦')
  router.push('/c-oj/home/exam')
}

const submitDTO = reactive({
  examId:'',
  questionId:'',
  programType: 0,
  userCode: ''
})

function handleEditorContent(content) {
  submitDTO.userCode = content
}

const userQuestionResultVO = ref({
  pass: 2,  //默认值为2，未提交代码
  exeMessage: '',
  userExeResultList: [],
})

const pollingInterval = ref(null);
let currentTime

function startPolling() {
  stopPolling(); // 停止之前的轮询
  pollingInterval.value = setInterval(() => {
    getQuestionResult();
  }, 2000); // 每隔2秒请求一次
}

function stopPolling() {
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value);
    pollingInterval.value = null;
  }
}

async function submitQuestion() {
  submitDTO.examId = examId
  submitDTO.questionId = questionId
  await userSubmitService(submitDTO)
  currentTime = new Date().toLocaleString();
  userQuestionResultVO.value.pass = 3
  startPolling()
}

async function getQuestionResult() {
  const res = await getQuestionResultService(submitDTO.examId, submitDTO.questionId, currentTime)
  userQuestionResultVO.value = res.data
  if (userQuestionResultVO.value.pass !== 3) {
    stopPolling();
  }
}

function goQuestTest(questionId) {
  if (!isLogin.value) {
    ElMessage.warning('请先登录后再开始答题')
    router.push('/c-oj/login')
    return
  }
  router.push(`/c-oj/answer?questionId=${questionId}`)
}

</script>

<style lang="scss" scoped>
.praticle-page {
  margin-top: -40px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .box_1 {
    background-color: #fff;
    height: 60px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    position: sticky;
    top: 0;
    z-index: 100;

    .group_1 {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 500;
      color: #303133;

      img {
        margin-right: 10px;
        width: 24px;
        height: 24px;
      }
    }

    .exam-time-countdown {
      margin: 0 0 0 400px;
      font-size: 14px;
      color: #409EFF;
    }

    .group_2 {
      .el-button {
        padding: 10px 20px;
        font-size: 14px;
        border-radius: 4px;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.2);
        }
      }
    }

    .ide-back {
      cursor: pointer;
      color: #909399;
      font-size: 14px;
      transition: color 0.3s;
      
      &:hover {
        color: #409EFF;
      }
    }
  }
}

.page {
  background-color: #f5f7fa;
  position: relative;
  min-height: calc(100vh - 60px);
  padding: 20px;

  .box_8 {
    position: relative;
    width: 100%;
    height: calc(100vh - 100px);

    .group_12 {
      width: 100%;
      height: 64px;
      margin-bottom: 20px;

      .image-wrapper_1 {
        background-color: #fff;
        border-radius: 8px;
        height: 64px;
        width: 600px;
        margin: 0 10px 0 0;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        display: flex;
        align-items: center;
        padding: 0 20px;

        .thumbnail_2 {
          width: 16px;
          height: 16px;
          margin-right: 10px;
        }

        .question-nav {
          cursor: pointer;
          margin-right: 100px;
          display: flex;
          align-items: center;
          color: #606266;
          transition: color 0.3s;
          
          &:hover {
            color: #409EFF;
          }

          .el-icon {
            margin: 0 5px;
          }
        }
      }

      .image-wrapper_2 {
        background-color: #fff;
        border-radius: 8px;
        height: 64px;
        display: flex;
        align-items: center;
        flex: 1;
        padding: 0 20px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        font-size: 16px;
        font-weight: 500;
        color: #303133;

        .image_1 {
          width: 20px;
          height: 20px;
          margin-right: 10px;
        }
      }
    }

    .group_13 {
      display: flex;
      justify-content: space-between;
      height: calc(100% - 84px);
      gap: 20px;

      .box_3 {
        width: 600px;
        background-color: #fff;
        padding: 24px;
        overflow-y: auto;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

        .question-title {
          font-size: 24px;
          font-weight: 600;
          margin-bottom: 20px;
          display: block;
          color: #303133;
        }

        .question-limit {
          color: #606266;
          margin-bottom: 20px;
          display: block;
          font-size: 14px;
          line-height: 1.6;
          padding: 12px;
          background-color: #f5f7fa;
          border-radius: 4px;
        }

        .question-content {
          line-height: 1.8;
          color: #303133;
          font-size: 15px;
        }
      }

      .group_14 {
        flex: 1;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        overflow: hidden;
        min-height: 600px;

        .group_8 {
          flex: 1;
          min-height: 500px;
          height: 60%;
        }

        .code-result {
          height: 48px;
          padding: 0 24px;
          align-items: center;
          border-top: 1px solid #ebeef5;
          background-color: #f5f7fa;
          flex-shrink: 0;

          .code-result-image {
            width: 20px;
            height: 20px;
            margin-right: 10px;
          }

          .code-result-content {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
          }
        }

        .group_15 {
          padding: 24px;
          background-color: #fff;
          height: 300px;  /* 设置固定高度 */
          overflow: hidden;  /* 隐藏溢出内容 */
          flex-shrink: 0;
        }

        .section_1 {
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
        }

        .section_3 {
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          overflow-y: auto;  /* 仅保留垂直滚动 */
          overflow-x: hidden;  /* 隐藏水平滚动 */
        }

        /* 表格容器样式 */
        .el-table {
          flex: 1;
          overflow: auto !important;  /* 允许表格内容滚动 */
        }

        /* 固定表头 */
        .el-table__header-wrapper {
          position: sticky;
          top: 0;
          z-index: 2;
          background-color: #fff;
        }

        /* 美化滚动条 */
        .section_3::-webkit-scrollbar,
        .el-table::-webkit-scrollbar {
          width: 8px;
          height: 8px;
        }

        .section_3::-webkit-scrollbar-thumb,
        .el-table::-webkit-scrollbar-thumb {
          background-color: #dcdfe6;
          border-radius: 4px;
        }

        .section_3::-webkit-scrollbar-track,
        .el-table::-webkit-scrollbar-track {
          background-color: #f5f7fa;
        }
      }
    }
  }
}

.flex-col {
  display: flex;
  flex-direction: column;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.justify-between {
  justify-content: space-between;
}

.text_1 {
  font-size: 16px;
  font-weight: 600;
  padding: 4px 8px;
  border-radius: 4px;
}

.text_1.success {
  color: #67c23a;  /* 绿色 */
}

.text_1.red {
  color: #f56c6c;  /* 红色 */
}

.text_1.warning {
  color: #e6a23c;  /* 橙色 */
}

.text_1.info {
  color: #909399;  /* 灰色 */
}

.error-text {
  color: #f56c6c;  /* 错误信息使用相同的红色 */
  font-size: 14px;
  margin-top: 8px;
  padding: 0 8px;
}
</style>